package cn.lili.controller.store;

import cn.lili.common.aop.annotation.DemoSite;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.goods.entity.dos.Category;
import cn.lili.modules.goods.entity.vos.CategoryVO;
import cn.lili.modules.goods.service.CategoryService;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.member.serviceimpl.ExtensionServiceImpl;
import cn.lili.modules.permission.entity.dos.Menu;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.dto.AdminStoreApplyDTO;
import cn.lili.modules.store.entity.dto.StoreEditDTO;
import cn.lili.modules.store.entity.vos.StoreDetailVO;
import cn.lili.modules.store.entity.vos.StoreManagementCategoryVO;
import cn.lili.modules.store.entity.vos.StoreSearchParams;
import cn.lili.modules.store.entity.vos.StoreVO;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.store.service.StoreEvaluationService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.aspect.annotation.SystemLogPoint;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import static cn.lili.common.enums.ResultCode.CATEGORY_NOT_EXIST;

/**
 * 管理端,店铺管理接口
 *
 * @author Bulbasaur
 * @since 2020/12/6 16:09
 */
@Api(tags = "管理端,店铺管理接口")
@RestController
@RequestMapping("/manager/store")
public class StoreManagerController {

	private Logger log = LoggerFactory.getLogger(StoreManagerController.class);
	/**
	 * 店铺
	 */
	@Autowired
	private StoreService storeService;
	/**
	 * 店铺详情
	 */
	@Autowired
	private StoreDetailService storeDetailService;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private StoreEvaluationService storeEvaluationService;

	@Autowired
	private PartnerService partnerService;

	@ApiOperation(value = "获取店铺分页列表")
	@RequestMapping("/all")
	public ResultMessage<List<Store>> getAll() {
		return ResultUtil.data(storeService.list(new QueryWrapper<Store>().eq("store_disable", "OPEN")));
	}

	@ApiOperation(value = "获取代理商推荐的店铺分页列表")
	@ApiImplicitParam(name = "userId", value = "代理商id", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/agent/{userId}")
	public ResultMessage<IPage<StoreVO>> pageByStoreVO(@PathVariable String userId, PageVO page) {
		QueryWrapper<Store> storeQueryWrapper = Wrappers.query();
		storeQueryWrapper.eq("m.id", userId);
		return ResultUtil.data(storeService.pageByStoreVO(page, storeQueryWrapper));
	}

	@ApiOperation(value = "获取店铺分页列表")
	@GetMapping
	public ResultMessage<IPage<StoreVO>> getByPage(StoreSearchParams entity, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			// 查询合伙人区域
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				entity.setAdCode(partner.getRegionId());
			}
		}
		return ResultUtil.data(storeService.findByConditionPage(entity, page));
	}

	@ApiOperation(value = "获取店铺分页列表")
	@RequestMapping("/findByConditionPageShenhe")
	public ResultMessage<IPage<StoreVO>> getByPageShenH(StoreSearchParams entity, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			// 查询合伙人区域
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				entity.setAdCode(partner.getRegionId());
			}
		}
		return ResultUtil.data(storeService.findByConditionPageShenhe(entity, page));
	}

	@ApiOperation(value = "获取异常店铺分页列表")
	@RequestMapping("/abnormalStore")
	public ResultMessage<IPage<StoreVO>> getAbnormalStoreByPage(StoreSearchParams entity, PageVO page) {
		entity.setGroupBySort(true);
		entity.setOrderByStoreEndTime(true);
		return ResultUtil.data(storeService.getAbnormalStoreByPage(entity, page));
	}

	@ApiOperation(value = "获取店铺详情")
	@ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String")
	@RequestMapping(value = "/get/detail/{storeId}")
	public ResultMessage<StoreDetailVO> detail(@PathVariable String storeId) {
		return ResultUtil.data(storeDetailService.getStoreDetailVO(storeId));
	}

	@ApiOperation(value = "添加店铺")
	@RequestMapping(value = "/add")
	@SystemLogPoint(description = "新增店铺", customerLog = "'新增店铺请求", type = "2")
	public ResultMessage<Store> add(@Valid AdminStoreApplyDTO adminStoreApplyDTO) {
		return ResultUtil.data(storeService.add(adminStoreApplyDTO));
	}

	@ApiOperation(value = "编辑店铺")
	@ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String")
	@PutMapping(value = "/edit/{id}")
	@SystemLogPoint(description = "编辑店铺", customerLog = "'编辑店铺请求", type = "2")
	public ResultMessage<Store> edit(@PathVariable String id, @Valid StoreEditDTO storeEditDTO) {
		storeEditDTO.setStoreId(id);
		return ResultUtil.data(storeService.edit(storeEditDTO));
	}

	@ApiOperation(value = "审核audit店铺申请")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "passed", value = "是否通过审核 0 通过 1 拒绝 编辑操作则不需传递", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "id", value = "店铺id", required = true, paramType = "path", dataType = "String")})
	@PutMapping(value = {"/audit/{id}/{passed}/{causer}", "/audit/{id}/{passed}"})
	@SystemLogPoint(description = "审核店铺", customerLog = "'审核店铺请求", type = "2")
	public ResultMessage<Object> audit(@PathVariable String id,
			@PathVariable(value = "passed", required = false) Integer passed,
			@PathVariable(value = "causer", required = false) String causer) {
		log.info("开始审核店铺");
		storeService.audit(id, passed, causer);
		return ResultUtil.success();
	}

	@DemoSite
	@ApiOperation(value = "注销店铺")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "店铺id", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "num", value = "返回现金", required = true, dataType = "String", paramType = "query")})
	@PutMapping(value = "/disable/{id}")
	@SystemLogPoint(description = "注销店铺", customerLog = "'注销店铺请求", type = "2")
	public ResultMessage<Store> disable(@PathVariable String id, String num) {
		storeService.disable(id, num);
		return ResultUtil.success();
	}

	@DemoSite
	@ApiOperation(value = "关闭店铺")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "店铺id", required = true, dataType = "String", paramType = "path")})
	@PutMapping(value = "/close/{id}")
	@SystemLogPoint(description = "关闭店铺", customerLog = "'关闭店铺请求", type = "2")
	public ResultMessage<Store> close(@PathVariable String id, String num) {
		storeService.close(id);
		return ResultUtil.success();
	}

	@ApiOperation(value = "开启店铺")
	@SystemLogPoint(description = "开启店铺", customerLog = "'开启店铺请求", type = "2")
	@ApiImplicitParam(name = "id", value = "店铺id", required = true, dataType = "String", paramType = "path")
	@PutMapping(value = "/enable/{id}")
	public ResultMessage<Store> enable(@PathVariable String id) {
		storeService.enable(id);
		return ResultUtil.success();
	}

	@ApiOperation(value = "查询一级分类列表")
	@ApiImplicitParam(name = "storeId", value = "店铺id", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/managementCategory/{storeId}")
	public ResultMessage<List<StoreManagementCategoryVO>> firstCategory(@PathVariable String storeId) {
		return ResultUtil.data(this.storeDetailService.goodsManagementCategory(storeId));
	}

	@ApiOperation(value = "根据会员id查询店铺信息")
	@RequestMapping("/{memberId}/member")
	public ResultMessage<Store> getByMemberId(@Valid @PathVariable String memberId) {
		List<Store> list = storeService.list(new QueryWrapper<Store>().eq("member_id", memberId));
		if (list.size() > 0) {
			return ResultUtil.data(list.get(0));
		}
		return ResultUtil.data(null);
	}

	@ApiOperation(value = "编辑店铺年费会员")
	@ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String")
	@RequestMapping(value = "/editHy")
	public ResultMessage<Store> editHy(@RequestParam String id, @RequestParam String memberCreateTime,
			@RequestParam String memberEndTime, @RequestParam Double payMoney) throws ParseException {
		Store store = new Store();
		store.setId(id);
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		store.setMemberCreateTime(fmt.parse(memberCreateTime));
		store.setMemberEndTime(fmt.parse(memberEndTime));
		store.setPayMoney(payMoney);
		return ResultUtil.data(storeService.edit(store));
	}

	@ApiOperation(value = "店铺推荐", notes = "店铺推荐")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "query", allowMultiple = true),
			@ApiImplicitParam(name = "recommend", value = "是否推荐", required = true, paramType = "query"),
			@ApiImplicitParam(name = "recommendRanking", value = "推荐排名", required = true, paramType = "query")})
	@PutMapping(value = "/recommend")
	public ResultMessage<Boolean> recommendGoods(@RequestParam String storeId, @RequestParam Boolean recommend,
			@RequestParam int recommendRanking) {

		return ResultUtil.data(storeService.updateRecommend(storeId, recommend, recommendRanking));
	}

	@ApiOperation(value = "获取分类列表")
	@RequestMapping(value = "/getCategoryByPid")
	public ResultMessage<List<Category>> getCategoryByPid(Long pid) {
		if (pid == null) {
			return ResultUtil.error(CATEGORY_NOT_EXIST);
		}
		return ResultUtil.data(storeService.getCategoryByPid(pid));
	}

	@ApiOperation(value = "获取全部分类列表")
	@RequestMapping(value = "/getAllCategory")
	public ResultMessage<List<CategoryVO>> getAllCategory() {
		return ResultUtil.data(this.categoryService.categoryTree());
	}

	@ApiOperation(value = "获取当前登录人的商家评分")
	@RequestMapping(value = "/storeScoreSum")
	public ResultMessage<Integer> storeScoreSum() {
		return ResultUtil.data(storeEvaluationService.storeScoreSum());
	}

	@ApiOperation(value = "店铺初审")
	@RequestMapping("/firstTrial")
	public ResultMessage<IPage<StoreVO>> getByFirstTrial(StoreSearchParams entity, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			// 查询合伙人区域
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				entity.setAdCode(partner.getRegionId());
			}
		}
		return ResultUtil.data(storeService.firstTrial(entity, page));
	}

	@ApiOperation(value = "初审通过拒绝")
	@RequestMapping(value = "/adopt")
	public ResultMessage<Store> adopt(Store store) {
		storeService.updateById(store);
		return ResultUtil.success();
	}

	@ApiOperation(value = "跟新店铺物流模板")
	@RequestMapping("/updateStoreFreightTemplate")
	@DemoSite
	public ResultMessage<Menu> updateStoreFreightTemplate() {
		storeService.updateStoreFreightTemplate();
		return ResultUtil.success();
	}

}
